package org.apache.qpid.management.common.sasl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.harmony.javax.security.auth.callback.Callback;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.auth.callback.NameCallback;
import org.apache.harmony.javax.security.auth.callback.PasswordCallback;
import org.apache.harmony.javax.security.auth.callback.UnsupportedCallbackException;

public class UsernameHashedPasswordCallbackHandler
  implements CallbackHandler
{
  private char[] pwchars;
  private String user;

  public UsernameHashedPasswordCallbackHandler(String paramString1, String paramString2)
    throws Exception
  {
    this.user = paramString1;
    this.pwchars = getHash(paramString2);
  }

  private void clearPassword()
  {
    int i;
    if (this.pwchars != null)
      i = 0;
    while (true)
    {
      if (i >= this.pwchars.length)
      {
        this.pwchars = null;
        return;
      }
      this.pwchars[i] = ';
      ++i;
    }
  }

  public static char[] getHash(String paramString)
    throws NoSuchAlgorithmException, UnsupportedEncodingException
  {
    byte[] arrayOfByte2;
    char[] arrayOfChar;
    int k;
    int l;
    int i1;
    byte[] arrayOfByte1 = paramString.getBytes("utf-8");
    MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
    int i = arrayOfByte1.length;
    int j = 0;
    if (j >= i)
    {
      arrayOfByte2 = localMessageDigest.digest();
      arrayOfChar = new char[arrayOfByte2.length];
      k = arrayOfByte2.length;
      l = 0;
      i1 = 0;
    }
    while (true)
    {
      while (l >= k)
      {
        return arrayOfChar;
        localMessageDigest.update(arrayOfByte1[j]);
        ++j;
      }
      int i2 = arrayOfByte2[l];
      int i3 = i1 + 1;
      arrayOfChar[i1] = (char)i2;
      ++l;
      i1 = i3;
    }
  }

  protected void finalize()
  {
    clearPassword();
  }

  public void handle(Callback[] paramArrayOfCallback)
    throws IOException, UnsupportedCallbackException
  {
    int i = 0;
    if (i >= paramArrayOfCallback.length)
      return;
    if (paramArrayOfCallback[i] instanceof NameCallback)
      ((NameCallback)paramArrayOfCallback[i]).setName(this.user);
    while (true)
    {
      while (true)
        ++i;
      if (!(paramArrayOfCallback[i] instanceof PasswordCallback))
        break;
      ((PasswordCallback)paramArrayOfCallback[i]).setPassword(this.pwchars);
    }
    throw new UnsupportedCallbackException(paramArrayOfCallback[i]);
  }
}